<script setup>
  import { reactive } from 'vue';
  import { onLoad } from '@dcloudio/uni-app';
  import { callCloudFunction } from '@/utils/cloudfunc';
  import { dateFormat } from '@/utils';
  
  import TnTabs from '@/uni_modules/tuniaoui-vue3/components/tabs/src/tabs.vue'
  import TnTabsItem from '@/uni_modules/tuniaoui-vue3/components/tabs/src/tabs-item.vue'
  import TnTitle from '@/uni_modules/tuniaoui-vue3/components/title/src/title.vue'
  import TnCountTo from '@/uni_modules/tuniaoui-vue3/components/count-to/src/count-to.vue'
  import TnLoadmore from '@/uni_modules/tuniaoui-vue3/components/loadmore/src/loadmore.vue'
  import QiunDataCharts from '@/uni_modules/qiun-data-charts/components/qiun-data-charts/qiun-data-charts.vue'
	import TnDateTimePicker from '@/uni_modules/tuniaoui-vue3/components/date-time-picker/src/date-time-picker.vue'
  
  const tabData = reactive({
    index: 0
  })
	
	// 日期设置
	const dateRange = reactive({
		startDate: new Date(),
		startDateStr: '',
		stsShow: '',
		openStartPicker: false,
		endDate: new Date(),
		endDateStr: '',
		etsShow: '',
		openEndPicker: false,
	})
  
  // 日期统计数据配置
  const statData = reactive({
    flagDate: new Date(),
		flagYear: new Date().getFullYear(),
    opts: {
      color: ['#5470c6', '#ee6666', '#73c0de','#fac858', '#3ba272', '#fc8452', '#91cc75', '#9a60b4', '#ea7ccc'],
    },
    dateStatList: [],
    dateStatChart: {},
    dateStatOpts: {
      color: ['#5470c6', '#ee6666', '#73c0de','#fac858', '#3ba272', '#fc8452', '#91cc75', '#9a60b4', '#ea7ccc'],
			dataLabel: false,
      xAxis: {
        rotateLabel: true,
				labelCount: 20,
      }
    },
    dateTotal: 0,
    monthStatList: [],
    monthStatChart: {},
    monthTotal: 0,
    yearStatList: [],
    yearStatChart: {},
    yearTotal: 0,
  })
  
  // 分类统计数据配置
  const cateData = reactive({
		statData: [],
		parentTotal: 0,
		parentIndex: 0,
    parentOpts: {
      color: ["#1890FF","#91CB74","#FAC858","#EE6666","#73C0DE","#3CA272","#FC8452","#9A60B4","#ea7ccc"],
      padding: [5,5,5,5],
      enableScroll: false,
      legend: {
        show: true,
        position: "left",
        lineHeight: 25
      },
      extra: {
        rose: {
          type: "area",
          minRadius: 60,
          activeOpacity: 0.5,
          activeRadius: 10,
          offsetAngle: 0,
          labelWidth: 15,
          border: false,
          borderWidth: 2,
          borderColor: "#FFFFFF",
          linearType: "custom"
        }
      }
    },
    parentChart: {
      series: [
        {
					// [{"name":"一班","value":50}]
          data: []
        }
      ]
    },
		childTotal: 0,
		childIndex: 0,
    childOpts: {
    },
    childChart: {
			series: []
		},
		billPage: 1,
		billSize: 10,
		billTotal: 0,
		billLoadStatus: 'loadmore',
    billList: [
		// {
  //     bill_date: '2024-01-01',
  //     bill_name: '测试账务',
  //     note: '备注',
  //     moneyStr: '66.6.00'
  //   },
		]
  })
  
  onLoad((options) => {
		// 设置日期
		const sts = new Date(statData.flagDate.getFullYear(), statData.flagDate.getMonth(), 1).getTime()
		const ets = new Date(statData.flagDate.getFullYear(), statData.flagDate.getMonth() + 1, 1).getTime() - 1000
		dateRange.startDate = sts
		dateRange.startDateStr = dateFormat(new Date(sts), '/', true)
		dateRange.stsShow = dateFormat(new Date(sts), 'ch', true)
		dateRange.endDate = ets
		dateRange.endDateStr = dateFormat(new Date(ets), '/', true)
		dateRange.etsShow = dateFormat(new Date(ets), 'ch', true)
    getStatData('date')
    getStatData('month')
    getStatData('year')
  })
  
  // 获取日期统计数据
  const getStatData = (type) => {
    if (!type) return
    let start_ts;
    let end_ts;
    let stat_type;
    if (type == 'date') {
      // flagDate所在的月份起始
      stat_type = '%Y-%m-%d'
      // start_ts = new Date(statData.flagDate.getFullYear(), statData.flagDate.getMonth(), 1).getTime()
			start_ts = dateRange.startDate
      // end_ts = new Date(statData.flagDate.getFullYear(), statData.flagDate.getMonth() + 1, 1).getTime() - 1000
			end_ts = dateRange.endDate
    } else if(type == 'month') {
      stat_type = '%Y-%m'
      start_ts = new Date(statData.flagYear, 0, 1).getTime()
      end_ts = new Date(statData.flagYear + 1, 0, 1).getTime() - 1000
    } else if (type == 'year') {
      stat_type = '%Y'
      start_ts = new Date(statData.flagDate.getFullYear() - 10, 0, 1).getTime()
      end_ts = new Date(statData.flagDate.getFullYear() + 1, 0, 1).getTime() - 1000
    } else {
      return
    }
    // 日期统计
    callCloudFunction({
      name: 'ledger-bill',
      data: {action: 'statBill', start_ts, end_ts, stat_type}
    }).then(res => {
      // console.log(res);
      const data = res.data
      // x轴名称
      let xAxis = []
      let numData = []
      let totalNum = 0
      for (let i = 0; i < data.length; i++) {
        let item = data[i]
        xAxis.push(data[i].name)
        let nStr = Number(data[i].totalMoney / 100).toFixed(2)
        numData.push(nStr)
        data[i].moneyStr = nStr
        totalNum += data[i].totalMoney
      }
      if (type == 'date') {
        statData.dateStatChart = {
          categories: xAxis,
          series: [{name: '日花销', data: numData}]
        }
        statData.dateTotal = Number(totalNum / 100).toFixed(2)
      } else if (type == 'month') {
        xAxis = xAxis.map(name => name.slice(5,) + '月')
        statData.monthStatChart = {
          categories: xAxis,
          series: [{name: '月花销', data: numData}]
        }
        statData.monthStatList = data
        statData.monthTotal = Number(totalNum / 100).toFixed(2)
      } else if (type == 'year') {
        statData.yearStatChart = {
          categories: xAxis,
          series: [{name: '年花销', data: numData}]
        }
        statData.yearStatList = data
        statData.yearTotal = Number(totalNum / 100).toFixed(2)
      } else  {}
      
    })
  }
  
	const getLedgerStatData = () => {
		const start_ts = dateRange.startDate
		const end_ts = dateRange.endDate
		callCloudFunction({
			name: 'ledger-bill',
			data: {action: 'cateStateBill', start_ts, end_ts}
		}).then(res => {
			// console.log('返回:', res)
			// 数据缓存
			cateData.statData = res.data.ledgerStat.filter(item => item.total > 0)
			// console.log('返回:', cateData.statData)
			const parentSeries = []
			let pTotal = 0
			cateData.statData.map(item => {
				pTotal += item.total
				parentSeries.push({
					name: item.category_name,
					value: Number((item.total/100).toFixed(2))
				})
			})
			// console.log('返回:', parentSeries)
			cateData.parentChart.series[0] = { data: parentSeries}
			cateData.parentTotal = Number((pTotal/100).toFixed(2))
			showChildChart(0)
		})
	}
	
	const loadMoreBill = () => {
		if (cateData.billLoadStatus == 'nomore') return
		cateData.billPage += 1
		getAccountList()
	}
	
	const getAccountList = () => {
		// const p = cateData.parentIndex
		const c = cateData.childIndex
		const obj = cateData.childChart.series[0].data[c]
		
		const ledger_id = obj.ledger_id
		// console.log(ledger_id);
		const start_ts = dateRange.startDate
		const end_ts = dateRange.endDate
		callCloudFunction({
			name:'ledger-bill',
			data: {
				action: 'getRangeLedgerPage', start_ts, end_ts, ledger_id,
				page: cateData.billPage, size: cateData.billSize
			}
		}).then(res => {
			// console.log('返回:', res);
			let bTotal = cateData.billPage > 1 ? Number(cateData.billTotal) * 100 : 0
			const resBills = res.bills.map(item => {
				bTotal += item.money
				return {
					bill_date: dateFormat(new Date(item.bill_time), '-', true),
					bill_name: item.bill_name,
					note: item.note,
					moneyStr: (item.money / 100).toFixed(2)
				}
			})
			if (cateData.billPage > 1) {
				cateData.billList = cateData.billList.concat(resBills)
			} else {
				cateData.billList = resBills
			}
			if (res.size > res.bills.length) {
				console.log('设置nomore');
				cateData.billLoadStatus = 'nomore'
			}
			cateData.billTotal = (bTotal/100).toFixed(2)
		})
	}
	
	const toOpenDatePicker = (action) => {
		if (action === 'start') {
			dateRange.openStartPicker = true
		} else if (action === 'end') {
			dateRange.openEndPicker = true
		}
	}
	
  const datePickerConfirm = () => {
		// console.log(dateRange.startDateStr);
		// console.log(dateRange.endDateStr);
		const s = new Date(dateRange.startDateStr)
		const e = new Date(dateRange.endDateStr)
		dateRange.stsShow = dateFormat(s, 'ch', true)
		dateRange.etsShow = dateFormat(e, 'ch', true)
		dateRange.startDate = s.getTime()
		dateRange.endDate = e.getTime()
		// 请求数据
		if (tabData.index == 0) {
			getStatData('date')
		}
		if (tabData.index == 1) {
			getLedgerStatData()
		}
	}
	
	const yearBarIndex = (e) => {
		const dataIndex = e.currentIndex.index
		const y = statData.yearStatChart.categories[dataIndex];
		statData.flagYear = parseInt(y)
		getStatData('month')
	}
	
	const tabChange = (e) => {
		// console.log(e)
		if (e === 0) {
			getStatData('date');
		} else if (e === 1) {
			getLedgerStatData();
		}
	}
	
	const showChildChart = () => {
		console.log('设置loadmore');
		const pieObj = cateData.statData[cateData.parentIndex]
		// console.log(pieObj)
		const childSeries = []
		let cTotal = 0
		pieObj.children.map(item => {
			if (item.total > 0) {
				cTotal += item.total;
				childSeries.push({
					name: item.category_name,
					value: Number((item.total/100).toFixed(2)),
					ledger_id: item._id,
				});
			}
		})
		// console.log('返回:', childSeries)
		cateData.childChart.series[0] = { data: childSeries }
		cateData.childTotal = Number((cTotal/100).toFixed(2))
		
		getAccountList()
	}
  
	const parentChartIndex = (e) => {
    // console.log(e);
		if (e.currentIndex == cateData.parentIndex) return
		cateData.parentIndex = e.currentIndex
		showChildChart()
  }
	const childChartIndex = (e) => {
		
		if (e.currentIndex == cateData.childIndex) return
		cateData.childIndex = e.currentIndex
		// 重置明细状态
		cateData.billPage = 1
		cateData.billLoadStatus = 'loadmore'
		getAccountList()
	}
</script>

<template>
  <view class="content">
		<TnDateTimePicker
			v-model="dateRange.startDateStr"
			v-model:open="dateRange.openStartPicker"
			mode='date'
			@confirm="datePickerConfirm"
		/>
		<TnDateTimePicker
			v-model="dateRange.endDateStr"
			v-model:open="dateRange.openEndPicker"
			mode='date'
			@confirm="datePickerConfirm"
		/>
    <view class="tn-mb-xs">
      <TnTabs v-model="tabData.index" @change='tabChange'>
        <TnTabsItem title="日期统计" />
        <TnTabsItem title="分类统计"/>
      </TnTabs>
    </view>
		<view class="tn-flex-center tn-mb-xs">
			<view class="tn-mr-xs tn-bluepurple_text" @click="toOpenDatePicker('start')">{{ dateRange.stsShow }}</view>
			<view>至</view>
			<view class="tn-ml-xs tn-orange_text" @click="toOpenDatePicker('end')">{{ dateRange.etsShow }}</view>
		</view>
    <view v-if="tabData.index == 0" class="fade-in">
      <view>
        <view class="title-node">
          <TnTitle title="日统计" mode="vLine" />
        </view>
        <view class="chart-box date">
          <QiunDataCharts
            type="line"
            :opts="statData.dateStatOpts"
            :chartData="statData.dateStatChart"
          />
        </view>
        <view class="bill-stat">
          <view class="stat-list">
            <view class="item stat">
              <view class="month">合计</view>
              <view class="num">￥<TnCountTo
                  start="0"
                  :end="statData.dateTotal"
                  :decimals="2" 
                  :duration="1000"
                  thousands-separator=","
              />&nbsp;元</view>
            </view>
          </view>
        </view>
      </view>
      <view>
        <view class="title-node tn-mt">
          <TnTitle title="月统计" mode="vLine" />
        </view>
        <view class="chart-box">
          <QiunDataCharts type="column" :opts="statData.opts" :chartData="statData.monthStatChart" />
        </view>
        <view class="bill-stat">
          <view class="stat-list">
            <view class="item" v-for="stat in statData.monthStatList">
              <view class="month">{{ stat.name }}</view>
              <view>{{ stat.moneyStr}}&nbsp;元</view>
            </view>
            <view class="item stat">
              <view class="month">合计</view>
              <view class="num">￥<TnCountTo
                  start="0"
                  :end="statData.monthTotal"
                  :decimals="2" 
                  :duration="1000"
                  thousands-separator=","
              />&nbsp;元</view>
            </view>
          </view>
        </view>
      </view>
      <view>
        <view class="title-node tn-mt">
          <TnTitle title="年统计" mode="vLine" />
        </view>
        <view class="chart-box">
          <QiunDataCharts
						type="column"
						:opts="statData.opts"
						:chartData="statData.yearStatChart"
						@getIndex="yearBarIndex"
					/>
        </view>
        <view class="bill-stat">
          <view class="stat-list">
            <view class="item" v-for="stat in statData.yearStatList">
              <view class="month">{{ stat.name }}</view>
              <view>{{ stat.moneyStr}}&nbsp;元</view>
            </view>
            <view class="item stat">
              <view class="month">合计</view>
              <view class="num">￥<TnCountTo
                  start="0"
                  :end="statData.yearTotal"
                  :decimals="2" 
                  :duration="1000"
                  thousands-separator=","
              />&nbsp;元</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view v-else-if="tabData.index == 1" class="fade-in">
      <view>
        <!-- 大类 -->
        <view class="title-node bg tn-flex">
          <TnTitle title="主类统计" mode="vLine" class="tn-flex-1" />
					<view class="tn-mr-sm">{{ cateData.parentTotal }}&nbsp;元</view>
        </view>
        <view class="chart-box">
          <QiunDataCharts
            type="rose"
            :opts="cateData.parentOpts"
            :chartData="cateData.parentChart"
            @getIndex="parentChartIndex"
          />
        </view>
      </view>
      <view>
        <!-- 子类 -->
        <view class="title-node bg tn-flex">
          <TnTitle title="细分类统计" mode="vLine" class="tn-flex-1" />
					<view class="tn-mr-sm">{{ cateData.childTotal }}&nbsp;元</view>
        </view>
        <view class="chart-box">
          <QiunDataCharts
            type="rose"
            :opts="cateData.parentOpts"
            :chartData="cateData.childChart"
						 @getIndex="childChartIndex"
          />
        </view>
      </view>
      <view>
        <!-- 明细分页 -->
        <view class="title-node bg tn-flex">
          <TnTitle title="账务明细" mode="vLine" class="tn-flex-1" />
					<view class="tn-mr-sm">{{ cateData.billTotal }}&nbsp;元</view>
        </view>
        <view class="bill-list tn-mt-sm">
          <template v-for="item in cateData.billList">
            <view class="item">
              <view class="b-date">
                {{ item.bill_date }}
              </view>
              <view class="bill-desc">
                <view class="name">
                  <text>{{ item.bill_name }}</text>
                  <text class="note">
                    {{ item.note}}
                  </text>
                </view>
              </view>
              <view class="amount">
                ￥{{ item.moneyStr }}
              </view>
            </view>
          </template>
        </view>
        <view class="tn-p">
          <TnLoadmore :status="cateData.billLoadStatus" @click="loadMoreBill" />
        </view>
      </view>
    </view>
  </view>
</template>


<style lang="scss" scoped>
  .content {
    // padding: 20rpx 0;
    .chart-box {
      height: 450rpx;
      &.date {
        height: 500rpx;
      }
    }
    .title-node {
      &.bg {
        background-color: #e8dfc4;
      }
    }
    .bill-stat {
      .stat-list {
        .item{
          display: flex;
          align-items: center;
          justify-content: space-between;
          border-bottom:1rpx solid #efefef;
          line-height: 50rpx;
          padding: 0 20rpx;
          &.stat {
            background-color: #e8dfc4;
          }
          .month {
            
          }
          .num {
            --tn-text-color-primary: #cb2d01;
          }
        }
      }
    }
    .bill-list {
      .item {
        display: flex;
        align-items: center;
        height: 60rpx;
        border-bottom: 1px solid #f9f9f9;
        padding: 10rpx 20rpx;
        .b-date {
          font-size: 25rpx;
          margin-right: 12rpx;
        }
        .bill-desc {
          flex: 1;
          .name {
            font-size: 30rpx;
            // line-height: 40rpx;
          }
          .note {
            font-size: 22rpx;
            color: #888;
            margin-left: 10rpx;
            // line-height: 30rpx;
          }
        }
        
        .amount {
          margin-left: auto;
          line-height: 70rpx;
        }
      }
    }
  }
</style>